import { getDateNow, getValidDate } from '@/dataTransfer/coupon';
import { useEffect, useRef } from 'react';
import { DAY_1, HOURS_1, MINUTE_1, SECOND_1 } from '../constants';
import interval from './interval';

function countdownSplit(duration) {
  let rest = duration;

  if (duration < 0) {
    return { finished: true };
  }

  const day = Math.floor(rest / DAY_1);
  rest -= day * DAY_1;

  const hour = Math.floor(rest / HOURS_1);
  rest -= hour * HOURS_1;

  const minute = Math.floor(rest / MINUTE_1);
  rest -= minute * MINUTE_1;

  const second = Math.floor(rest / SECOND_1);
  rest -= second * SECOND_1;

  const millisecond = rest;

  return { day, hour, minute, second, millisecond };
}

const calculate = (start, end) => {
  const now = getDateNow();

  if (start) {
    const startDuration = getValidDate(start).getTime() - now;

    // 未开始
    if (startDuration > 0) {
      return { start: countdownSplit(startDuration) };
    }
  }

  const endTime = getValidDate(end).getTime();

  // 已结束
  if (now > endTime) {
    return { finished: true };
  }

  // 已开始, 未结束
  let endDuration = endTime - now;
  return { end: countdownSplit(endDuration) };
};

const useCountdown = (cb, start, end = start) => {
  const callbackRef = useRef(() => {});

  // 设置 定时器执行 脚本
  useEffect(() => {
    callbackRef.current = () => {
      const result = calculate(start, end);

      // 不再需要定时刷新了
      if (result?.finished) {
        interval.del(callbackRef);
      }

      cb(result);
    };
  }, [cb, start, end]);

  useEffect(() => {
    // 先执行一次
    callbackRef.current();

    // 加入队列
    interval.add(callbackRef);

    // 从队列删除
    return () => {
      interval.del(callbackRef);
    };
  }, [callbackRef]);

  // 返回清除定时器
  return () => {
    interval.del(callbackRef);
  };
};

export { useCountdown, calculate };
